﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using DevExpress.XtraTreeList.Nodes;
using System;
using XCI.Extensions;
using XCI.Sys.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Windows.Extensions;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统模块管理
    /// </summary>
    [FormCaption("系统模块管理")]
    public partial class FrmModuleManager : FrmSysBase
    {
        private TreeHelper<SysModule> helper;
        private ModuleHelper moduleHelper;
        private readonly bool allowSelect = SysRuntime.IsAuthorize("sys.module.select");
        private readonly bool allowInsert = SysRuntime.IsAuthorize("sys.module.insert");
        private readonly bool allowUpdate = SysRuntime.IsAuthorize("sys.module.update");
        private readonly bool allowDelete = SysRuntime.IsAuthorize("sys.module.delete");
        private readonly bool allowExport = SysRuntime.IsAuthorize("sys.module.export");

        public FrmModuleManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void InitForm()
        {
            //1.初始化表格操作类
            moduleHelper = new ModuleHelper(tree);
            helper = new TreeHelper<SysModule>(tree);
            helper.ElapsedTimeItem = labExecuteTime;
            helper.AutoCheckedChildNode = true;
            helper.IsReserveNodeExpandedStatus = true;
            helper.IsReserveNodeFocused = true;
            helper.ModifyData += Helper_ModifyData;
            helper.NodeChecked += Helper_NodeChecked;

            //2.加载数据
            LoadData();
            ButtonStatus();
        }

        private void Helper_NodeChecked(object sender, EventArgs e)
        {
            ButtonStatus();
        }

        /// <summary>
        /// 更新节点顺序和父节点
        /// </summary>
        private void Helper_ModifyData(object sender, EventArgs e)
        {
            var list = helper.GetChangedDataList();
            helper.ClearDataChanged();
            ModuleService.Instance.BatchUpdateValues(list);
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        private void LoadData()
        {
            //权限控制
            if (!allowSelect) return;

            var status = statusCombo.SelectedValue.ToBoolOrNull();
            helper.RunCallback(e =>
            {
                e.Result = ModuleService.Instance.SelectList(status);
            })
            .CompletCallback(e =>
            {
                tree.Filter();
                ButtonStatus();
                moduleHelper.InitModuleImageList(treeImageList, false);

                OnceAction("firstExpandNode", () =>
                {
                    moduleHelper.ExpandNode();
                });
            })
            .RunAsync();
        }

        /// <summary>
        /// 数据编辑
        /// </summary>
        /// <param name="created">是否新建</param>
        /// <param name="parentNode">父节点对象</param>
        /// <param name="model">模型对象</param>
        private void Edit(bool created, TreeListNode parentNode, SysModule model)
        {
            if (model.MenuFlag.HasValue && model.MenuFlag.Value)
            {
                var editForm = new FrmModuleEdit();
                editForm.SetModel(created, model, helper.Get(parentNode));
                editForm.ShowDialogOk(LoadData);
            }
            else
            {
                var editForm = new FrmPermissionEdit();
                editForm.SetModel(created, model, helper.Get(parentNode));
                editForm.ShowDialogOk(LoadData);
            }
        }

        /// <summary>
        /// 获取选中的对象
        /// </summary>
        /// <returns>返回选中的对象</returns>
        private SysModule GetSelected()
        {
            return ModuleService.Instance.SelectById(helper.SelectedId);
        }

        /// <summary>
        /// 设置按钮可用状态
        /// </summary>
        private void ButtonStatus()
        {
            var isSingle = !helper.HasMultiSelected && !helper.HasMultiChecked && helper.HasSelected;
            btnNewMenu.Enabled = btnNewPermission.Enabled = allowInsert;
            btnEdit.Enabled = isSingle && allowUpdate;
            btnCopy.Enabled = isSingle && allowInsert;
            btnDelete.Enabled = helper.HasChecked && allowDelete;
            btnExport.Enabled = helper.HasData && allowExport;
            btnRefresh.Enabled = allowSelect;
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void FrmModuleManager_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void tree_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            ButtonStatus();
        }

        private void tree_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = moduleHelper.GetModuleImageIndex(e.Node);
        }

        private void tree_DoubleClick(object sender, EventArgs e)
        {
            helper.DblClickRow(e, () =>
            {
                var detailsForm = new FrmModuleDetails(helper.SelectedId);
                detailsForm.ShowDialogOk();
            });
        }

        private void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            EndInit(LoadData);
        }

        private void BtnNewMenu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, tree.FocusedNode, ModuleService.Instance.NewMenu());
        }

        private void BtnNewPermission_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, tree.FocusedNode, ModuleService.Instance.NewPermission());
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(false, tree.FocusedNode.ParentNode, GetSelected());
        }

        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, tree.FocusedNode.ParentNode, ModuleService.Instance.Copy(GetSelected()));
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            helper.DeleteByChecked(() =>
            {
                ModuleService.Instance.Delete(helper.CheckedIds).IfTrue(LoadData);
            });
        }

        private void BtnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadData();
        }

        private void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var status = statusCombo.SelectedValue.ToBoolOrNull();
            ExcelExportCore(() => ModuleService.Instance.Export(status), "系统模块");
        }
    }
}